package com.kaidi.dibankecloud.activity;

import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.PopupWindow;

import com.kaidi.dibankecloud.R;
import com.kaidi.dibankecloud.databinding.ActivityMainBinding;
import com.kaidi.dibankecloud.utils.WindowUtils;
import com.kaidi.dibankecloud.widget.TipsPopupWindow;
import com.kaidi.dibankecloud.widget.VerificationCode;

public class MainActivity extends AppCompatActivity implements PopupWindow.OnDismissListener {
    private ActivityMainBinding binding;
    private String verCode;
    private boolean accountInputError;
    private boolean verCodeError;
    private TipsPopupWindow tipsPopupWindow;
    //用户账户
    private String account;
    //用户密码
    private String pwd;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
        //沉浸式状态栏设计
        WindowUtils.setColor(this,ContextCompat.getColor(this, R.color.colorHighlightBlue));
        //设置字体
        Typeface tf = Typeface.createFromAsset(getAssets(), "fonts/fzltxhjt.ttf");
        binding.setLoginTypeFace(tf);
        //设置验证码
        setVerificationCode();
        //设置文本监听器
        binding.loginAccountEt.addTextChangedListener(new LoginTextWatcher(LoginTextWatcher.ACCOUNT_WATCHER));
        binding.loginPwdEt.addTextChangedListener(new LoginTextWatcher(LoginTextWatcher.PASSWORD_WATCHER));
        binding.loginVerCodeEt.addTextChangedListener(new LoginTextWatcher(LoginTextWatcher.VER_CODE_WATCHER));
        binding.setTargetActivityClass(RegisterActivity.class);
    }

    /**
     * 清空按钮、密码可见按钮点击事件
     */
    public void loginActivityClick(View view){
        switch (view.getId()) {
            case R.id.login_account_clear_btn:
                binding.loginAccountEt.setText("");
                break;
            case R.id.login_pwd_clear_btn:
                binding.loginPwdEt.setText("");
                break;
            case R.id.login_pwd_show_btn:
                if(binding.loginPwdEt.getInputType() == 0x81) {
                    binding.loginPwdEt.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                }else{
                    binding.loginPwdEt.setInputType(0x81);
                }
                break;
            case R.id.login_refresh_ver_code_iv:
                setVerificationCode();
                break;
            case R.id.login_btn:
                if(!login()){
                    setVerificationCode();
                }
                break;
            case R.id.login_bottom_text_reg:
                startActivity(new Intent(this,RegisterActivity.class));
                break;
        }
    }

    /**
     * 登录
     */
    public boolean login(){
        if(checkVerificationCode()){
            initErrorTextView();
            if (!((BaseApplication) getApplication()).isNetConnected()) {
                showTipsPopupWindow(getResources().getDrawable(R.drawable.ic_login_error),getString(R.string.network_error), Color.BLACK);
            }else{
                showTipsPopupWindow(getResources().getDrawable(R.drawable.ic_login_in_process),getString(R.string.login_in_process),getResources().getColor(R.color.colorHighlightBlue));

                new CountDownTimer(3000,1000){
                    @Override
                    public void onTick(long l) {}
                    @Override
                    public void onFinish() {
                        int responseCode = 100;
                        if(responseCode != 200){
                            if (checkAccount()) {
                                showTipsPopupWindow(getResources().getDrawable(R.drawable.ic_login_fail),getString(R.string.login_failed_please_try_again),Color.BLACK);
                            }else{
                                //跳转到登陆后的页面
                            }
                        }
                    }
                }.start();

            }
            return true;
        }
        return false;
    }

    /**
     * 设置验证码的方法
     */
    public void setVerificationCode(){
        binding.loginVerCodeIv.setImageBitmap(VerificationCode.getInstance().createBitmap());
        verCode = VerificationCode.getInstance().getCode();
    }

    /**
     * 校验验证码的方法
     */
    public boolean checkVerificationCode(){
        if(!binding.loginVerCodeEt.getText().toString().equalsIgnoreCase(verCode)){
            verCodeError = true;
            binding.loginErrorTv.setText(getString(R.string.ver_code_wrong));
            binding.loginVerCodeEt.setBackgroundResource(R.drawable.et_login_ver_error);
            return false;
        }
        return true;
    }

    /**
     * 校验账号密码的方法
     */
    public boolean checkAccount(){
        String checkResult;
        account = binding.loginAccountEt.getText().toString();
        pwd = binding.loginPwdEt.getText().toString();
        if(!account.equals("123456")){
            checkResult = getString(R.string.account_not_exist);
        }else if(!pwd.equals("123456")){
            checkResult = getString(R.string.account_or_pwd_wrong);
        }else{
            return true;
        }
        accountInputError = true;
        binding.loginPfl.setBackgroundResource(R.drawable.bg_login_red);
        binding.loginErrorTv.setText(checkResult);
        return false;
    }

    /**
     * 初始化输入框背景状态
     */
    public void initEditTextBackground(int textWatcherFlag){
        switch (textWatcherFlag) {
            case LoginTextWatcher.ACCOUNT_WATCHER:
            case LoginTextWatcher.PASSWORD_WATCHER:
                if(accountInputError) {
                    binding.loginPfl.setBackgroundResource(R.drawable.bg_login_gray);
                    accountInputError = false;
                }
                break;
            case LoginTextWatcher.VER_CODE_WATCHER:
                if(verCodeError) {
                    binding.loginVerCodeEt.setBackgroundResource(R.drawable.et_login_ver_normal);
                    verCodeError = false;
                }
                break;
        }
        initErrorTextView();
    }

    /**
     * 初始化错误信息提示框的方法
     */
    public void initErrorTextView(){
        if(!TextUtils.isEmpty(binding.loginErrorTv.getText())){
            binding.loginErrorTv.setText("");
        }
    }


    /**
     * 检测清空按钮、密码可见按钮是否可用的方法
     */
    public void checkSmallBtnEnabled(CharSequence charSequence, Button... buttons){
        if(charSequence != null && !TextUtils.isEmpty(charSequence)){
            if(!buttons[0].isEnabled()) {
                buttons[0].setEnabled(true);
            }
            if(buttons.length > 1){
                if(buttons[1].getVisibility() == View.INVISIBLE){
                    buttons[1].setVisibility(View.VISIBLE);
                }
            }
        }else{
            buttons[0].setEnabled(false);
            if(buttons.length > 1){
                buttons[1].setVisibility(View.INVISIBLE);
            }
        }
    }

    /**
     * 检测登录按钮是否可用的方法
     */
    public void checkLoginBtnEnabled(){
        String account = binding.loginAccountEt.getText().toString();
        String pwd = binding.loginPwdEt.getText().toString();
        String verCode = binding.loginVerCodeEt.getText().toString();
        if(accountInputError || verCodeError || TextUtils.isEmpty(account)
                                || TextUtils.isEmpty(pwd) || TextUtils.isEmpty(verCode)){
            binding.loginBtn.setEnabled(false);
        }else{
            initErrorTextView();
            binding.loginBtn.setEnabled(true);
        }
    }

    /**
     * 显示tipsPopupWindow的方法
     */
    public void showTipsPopupWindow(Drawable tipsIcon,String tipsText,int textColor){
        if(tipsPopupWindow != null && tipsPopupWindow.isShowing()){
            tipsPopupWindow.dismiss();
        }
        tipsPopupWindow = new TipsPopupWindow(this,tipsIcon,tipsText,textColor);
        if(!tipsText.equals(getString(R.string.login_in_process))){
            tipsPopupWindow.setOutsideTouchable(true);
        }
        tipsPopupWindow.showPopupWindow(binding.getRoot());
        tipsPopupWindow.setOnDismissListener(this);
    }

    /**
     * tipsPopupWindow 消失监听器
     */
    @Override
    public void onDismiss() {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = 1f;
        getWindow().setAttributes(lp);
    }

    /**
     * 文本输入框 内容监视者内部类
     */
    private class LoginTextWatcher implements TextWatcher{
        private  static final int ACCOUNT_WATCHER = 101;
        private  static final int PASSWORD_WATCHER = 202;
        private  static final int VER_CODE_WATCHER = 303;
        private  int flag;

        private LoginTextWatcher(int flag) {
            this.flag = flag;
        }

        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {}
        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {}
        @Override
        public void afterTextChanged(Editable editable) {
            switch (flag) {
                case ACCOUNT_WATCHER:
                    checkSmallBtnEnabled(editable.toString(),binding.loginAccountClearBtn);
                    break;
                case PASSWORD_WATCHER:
                    checkSmallBtnEnabled(editable.toString(),binding.loginPwdShowBtn,binding.loginPwdClearBtn);
                    break;
            }
            if(accountInputError || verCodeError) {
                initEditTextBackground(flag);
            }
            checkLoginBtnEnabled();
        }
    }
}
